package net.liuzd.spring.boot.v2.util;

import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.util.UUID;

public class JavaDownloadFileFromURL {

    public static void main(String[] args) {
        // https://www.journaldev.com/924/java-download-file-url
        String url = "https://avatars1.githubusercontent.com/u/1787798?s=460&v=4";
        String fileName = UUID.randomUUID().toString() + ".png";
        //
        try {
            String rootPath = "D:\\download-file\\";
            //
            long s = System.currentTimeMillis();
            downloadUsingNIO(url, rootPath + "1-" + fileName);
            long e = System.currentTimeMillis();
            System.out.println("1 : " + (e - s));
            //
            s = System.currentTimeMillis();
            downloadUsingStream(url, rootPath + "2-" + fileName);
            e = System.currentTimeMillis();
            System.out.println("2 : " + (e - s));
            //
            //
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void downloadUsingStream(String urlStr, String file) throws IOException {
        URL url = new URL(urlStr);
        BufferedInputStream bis = new BufferedInputStream(url.openStream());
        FileOutputStream fis = new FileOutputStream(file);
        byte[] buffer = new byte[1024];
        int count = 0;
        while ((count = bis.read(buffer, 0, 1024)) != -1) {
            fis.write(buffer, 0, count);
        }
        fis.close();
        bis.close();
    }

    private static void downloadUsingNIO(String urlStr, String file) throws IOException {
        URL url = new URL(urlStr);
        ReadableByteChannel rbc = Channels.newChannel(url.openStream());
        FileOutputStream fos = new FileOutputStream(file);
        fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
        fos.close();
        rbc.close();
    }

}